/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.net;

import java.net.SocketAddress;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import jp.aist.gtrc.plus.scheduler.util.TimeUtil;

import org.apache.log4j.Logger;


public class AcceptChecker {

	private Map<SocketAddress, AllowedClient> allowed;
	private int allowedTimeout;
	private static final int DEFAULT_TIMEOUT = 10;	// [sec]

	protected static final  Logger logger = Logger.getLogger(AcceptChecker.class);

	public AcceptChecker() {

		allowed = new HashMap<SocketAddress, AllowedClient>();
		allowedTimeout = DEFAULT_TIMEOUT;

	}

	public void setAllowedTimeout(int sec){

		this.allowedTimeout = sec;

	}

	public synchronized void addAllowedClient(SocketAddress client){

		// purge old information if duplicate
		if (allowed.containsKey(client)) {
			logger.debug("remove old auth info");
			allowed.remove(client);
		}

		logger.debug("Add allowed: " + client.toString());
		allowed.put(client, new AllowedClient(client));

	}

	public synchronized void removeAllowedClient(SocketAddress client){

		if (allowed.containsKey(client)) {
			logger.debug("Del allowed: " + client.toString());
			allowed.remove(client);
		} else {
			/*
			 * GuardedSocket#close() will be called 2 times because of
			 * RMI implementation by SUN.
			 * Ignore duplicate call of this method.
			 */
		}

	}

	private boolean isExpired(AllowedClient allowedClient) {

		int now = TimeUtil.calToSec(Calendar.getInstance());
		int regTime = TimeUtil.calToSec(allowedClient.getAllowedTime());

		return ((now - regTime) > allowedTimeout);

	}

	public synchronized boolean isAllowed(SocketAddress client){

		logger.debug("Check: " + client.toString());

		AllowedClient allowedClient = allowed.get(client);
		if (allowedClient == null) {
			logger.warn("Unauthrized client: " + client.toString());
			return false;	// unknown client
		}

		logger.debug(allowedClient.toString());

		if (isExpired(allowedClient)) {
			logger.warn("Auth expired");
			return false;	// authentication is expired
		}

		return true;		// OK to connect

	}

}
